//
//  MessageSearchViewController.swift
//  ezyform
//
//  Created by Hubert on 2022/5/9.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
import SwiftyJSON

class MessageSearchViewController: BaseViewController {
    // 是否显示搜索记录
    let historyListCacheKey = (APPConfig.loginInfo.email) + "-NotificationSearchHistory"
    private var historyList: [String] = []
    // 是否显示搜索记录
    private var isHistory: Bool = true
    private var dataArray: [NotificationModel] = []
    let customView = BaseSearchView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
        self.loadHistoryList()
    }
    func initUI(){
        self.view = self.customView
        self.customView.cancelBtn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        self.customView.searchTextField.delegate = self
        self.customView.searchTextField.becomeFirstResponder()
        self.customView.tableView.delegate = self
        self.customView.tableView.dataSource = self
    }
    func loadData(){
        let service = NotificationService()
        service.setBlockAfterNetwork({ [weak self] (result, otherInfo) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            guard let self = self else { return }
            
            let json = JSON(result!)
            if let list = JSONDeserializer<NotificationModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<NotificationModel>{
                self.dataArray = list
                DispatchQueue.main.async {
                    self.customView.tableView.reloadData()
                }
            }
            //没有数据显示not data view，有数据隐藏not data view
            self.customView.tableView.showResultView(nodataFlag: self.dataArray.count == 0 ? true: false)
            
        }, errorBlock: { (code, error) -> Void in
            ModelViewUtil.shared.hideLoadingView()
            self.isHistory = true
            Tool().showErrorInfo(code, error)
        })
        ModelViewUtil.shared.showLoadingView()
        service.getNotificationListWithoutCache("1", searchText: self.customView.searchTextField.text ?? "")
    }
    
    // MARK: - loadHistoryList
    private func loadHistoryList() {
        if isHistory {
            historyList = UserDefaults.standard.stringArray(forKey: historyListCacheKey) ?? []
            self.customView.tableView.reloadData()
        }
    }
    
    override func  touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    @objc func cancelAction() {
        self.dismiss(animated: false)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
extension MessageSearchViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if self.isHistory == false {
            self.isHistory = true
            self.customView.tableView.backgroundView = nil
            self.customView.tableView.reloadData()
        }
        return true
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if textField.text?.count == 0 {
            self.isHistory = true
        } else {
            startSearch()
        }
        return true
    }
    
    // MARK: - 开始搜索
    func startSearch(){
        view.endEditing(true)
        if let text = self.customView.searchTextField.text, text.trimmingCharacters(in: .whitespaces) != ""{
            let realSearchText = text.trimmingCharacters(in: .whitespaces)
            //如果历史列表中不存在当前搜索内容就增加在第一行
            if let findIndex = self.historyList.firstIndex(where: { $0 == realSearchText}){//如果存在就删除，
                self.historyList.remove(at: findIndex)
            }
            //把当前条码放在最前边
            self.historyList.insert(realSearchText, at: 0)
            if self.historyList.count > 10 {
                self.historyList.removeLast()
            }
        }
        UserDefaults.standard.set(self.historyList, forKey: self.historyListCacheKey)
        UserDefaults.standard.synchronize()
        self.isHistory = false
        self.loadData()
    }
}

extension MessageSearchViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if self.isHistory {
            var cell : MessageHistoryTableViewCell? = tableView.dequeueReusableCell(withIdentifier: MessageHistoryTableViewCell.reuseCellIdentifier) as? MessageHistoryTableViewCell
            if (cell == nil){
                cell = MessageHistoryTableViewCell(style: .default, reuseIdentifier: MessageHistoryTableViewCell.reuseCellIdentifier)
            }
            cell?.setData(self.historyList[indexPath.row])
            cell?.closeClosure = { [weak self] in
                guard let self = self else { return }
                self.historyList.remove(at: indexPath.row)
                UserDefaults.standard.set(self.historyList, forKey: self.historyListCacheKey)
                UserDefaults.standard.synchronize()
                DispatchQueue.main.async {
                    self.customView.tableView.reloadData()
                }
            }
            return cell!
        } else {
            var cell : MessageTableViewCell? = tableView.dequeueReusableCell(withIdentifier: MessageTableViewCell.reuseCellIdentifier) as? MessageTableViewCell
            if (cell == nil){
                cell = MessageTableViewCell(style: .default, reuseIdentifier: MessageTableViewCell.reuseCellIdentifier)
            }
            let model = self.dataArray[indexPath.row]
            cell?.setData(model)
            return cell!
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.isHistory {
            return self.historyList.count
        } else {
            return self.dataArray.count
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.isHistory {
            self.customView.searchTextField.text = self.historyList[indexPath.row]
            startSearch()
        } else {
            let model = self.dataArray[indexPath.row]
            let vc = MessageDetailViewController()
            vc.refreshListBlock = { [weak self] in //设置成已读状态
                guard let strongSelf = self else { return }
                if let indexRow = strongSelf.dataArray.firstIndex(where: { $0.id == model.id}) {
                    strongSelf.dataArray[indexRow].is_read = true
                    strongSelf.customView.tableView.reloadRows(at: [IndexPath(row: indexRow, section: 0)], with: UITableView.RowAnimation.none)
                }
            }
            vc.id = model.id
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
}
